package com.zhl.test;

import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;

public class 方法二 {
	/*
	 * trustEveryone()方法可以忽略HTTPS的证书验证
	 * 使用JSOUP抓取页面
	 * 
	 */
	 public static void main(String[] args) {    
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		 String date = sdf.format(new Date());
		 //从12306查询当天广州东——深圳的火车票
	     String url = "https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date="+date+"&leftTicketDTO.from_station=GGQ&leftTicketDTO.to_station=SZQ&purpose_codes=ADULT";       
	     trustEveryone();   
         Response res = null;
         Document document = null;
		 try {
			res = Jsoup.connect(url)
						//忽略不加上header参数的报错
						.timeout(1000)
						.ignoreContentType(true)
						.execute();
			document = res.parse();
			
		 } catch (IOException e) {

			e.printStackTrace();
		 }


		String result = document.text();    

		System.out.println(result);
  
	} 
	

    
    public static void trustEveryone() {   
        try {    
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {    
                public boolean verify(String hostname, SSLSession session) {    
                    return true;    
                }    
            });    
    
            SSLContext context = SSLContext.getInstance("TLS");    
            context.init(null, new X509TrustManager[] { new X509TrustManager() {    
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {    
                }    
    
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {    
                }    
    
                public X509Certificate[] getAcceptedIssuers() {    
                    return new X509Certificate[0];    
                }    
            } }, new SecureRandom());    
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());    
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
    }    
    

    
     
}
